<?php
namespace PsiFramework\Classes\Util\Object;

import("Classes.Model.ModelInterface.IPrimitiveObject");
import("Classes.Util.Object.Json");
import("Classes.Factory.DAOFactory");
import("Classes.Util.Manager.ObjectManager");
import("Classes.Util.Database.Query.SqlType");

use \PsiFramework\Classes\Util\Database\Query\SqlType;
use \PsiFramework\Classes\Model\ModelInterface\IPrimitiveObject;
use \PsiFramework\Classes\Util\Object\Json;
use \PsiFramework\Classes\Factory\DAOFactory;
use \PsiFramework\Classes\Util\Manager\ObjectManager;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 *
 *
 * @package Util.Parameters
 */
class ReferenceObject implements IPrimitiveObject
{

    protected /*string*/ $_type ;
    protected /*mixed*/  $_value ;

    public function __construct(/*string*/ $type=null, /*mixed*/ $value=null)
    {
        $this->_type = $type ;
        $this->_value = $value ;
    }

    public function getType()
    {
        return $this->_type ;
    }

    public function setType(/*string*/ $type)
    {
        $this->_type = $type ;
    }

    public function getValue()
    {
        return $this->_value ;
    }

    public function setValue(/*int*/ $value)
    {
        $this->_value = $value ;
    }

    public function getObject(/*bool*/ $forceReloadFromBase=false, /*bool*/ $checkSecurity=true)
    {
        if (ObjectManager::getInstance()->isObject($this->_type)) {
            $dao = DAOFactory::getDAO($this->_type);
            return $dao->retrieveByPk($this->_value, $forceReloadFromBase, $checkSecurity);
        } else {
            return $this->_value ;
        }
    }

    public function serialize(/*boolean*/ $asText=true)
    {

        $value = null ;
        if ($this->_value instanceof IPrimitiveObject) {
            $value = $this->_value->serialize(false);
        } else {
            $value = $this->_value ;
        }

        $json = new \stdClass();
        $json->type = $this->_type ;
        $json->value = $value ;

        $jsonObject = new Json($json);

        return $jsonObject->serialize($asText);
    }

    public function unserialize($value)
    {
        $jsonObject = new Json();
        $jsonObject->unserialize($value);

        $type = $jsonObject->getObject()->type ;
        $jsonValue = $jsonObject->getObject()->value ;

        $value = ObjectManager::getInstance()->
            getPrimitiveObjectInstance($type);
        if (!is_null($value)) {
            $value->unserialize($jsonValue);
        } else {
            $value = $jsonValue ;
        }

        $this->_type = $type ;
        $this->_value = $value ;
    }

    public function toString()
    {
        
    }

    public static function getSqlType()
    {
        return SqlType::$text ;
    }
}
